import React, { useState, useCallback } from 'react';
import { Play, Pause, Square } from 'lucide-react';
import { FileList } from './FileList';
import { ProcessSettings } from './ProcessSettings';
import { BatchProgress } from './BatchProgress';
import { VideoFile, ProcessTask, TaskStatus, TaskType } from '@/types/video';
import './styles.less';

interface BatchProcessorProps {
  className?: string;
}

export const BatchProcessor: React.FC<BatchProcessorProps> = ({ className = '' }) => {
  const [selectedFiles, setSelectedFiles] = useState<VideoFile[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [tasks, setTasks] = useState<ProcessTask[]>([]);
  const [currentTask, setCurrentTask] = useState<ProcessTask | null>(null);

  // 处理文件选择
  const handleFilesSelected = useCallback((files: VideoFile[]) => {
    setSelectedFiles(files);

    // 为每个文件创建处理任务
    const newTasks = files.map(file => ({
      id: `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      type: 'convert' as TaskType,
      status: 'pending' as TaskStatus,
      progress: {
        percentage: 0,
        currentFrame: 0,
        totalFrames: 0,
        fps: 0,
        timeElapsed: 0,
        timeRemaining: 0,
        currentPhase: '等待开始',
      },
      inputFiles: [file],
      outputPath: '',
      options: {},
      createdAt: new Date(),
      startedAt: undefined,
      completedAt: undefined,
      estimatedDuration: 0,
    }));

    setTasks(newTasks);
  }, []);

  // 开始批量处理
  const handleStartProcessing = useCallback(async () => {
    setIsProcessing(true);

    // 模拟处理过程
    for (let i = 0; i < tasks.length; i++) {
      const task = tasks[i];
      setCurrentTask(task);

      // 更新任务状态为处理中
      setTasks(prev =>
        prev.map(t =>
          t.id === task.id ? { ...t, status: 'processing', startedAt: new Date() } : t
        )
      );

      // 模拟处理进度
      for (let progress = 0; progress <= 100; progress += 10) {
        await new Promise(resolve => setTimeout(resolve, 300));

        setTasks(prev =>
          prev.map(t =>
            t.id === task.id
              ? {
                  ...t,
                  progress: {
                    ...t.progress,
                    percentage: progress,
                    currentPhase: progress < 50 ? '编码视频' : '处理音频',
                    timeElapsed: (Date.now() - (t.startedAt?.getTime() || Date.now())) / 1000,
                  },
                }
              : t
          )
        );
      }

      // 任务完成
      setTasks(prev =>
        prev.map(t =>
          t.id === task.id
            ? {
                ...t,
                status: 'completed',
                completedAt: new Date(),
                progress: { ...t.progress, percentage: 100, currentPhase: '完成' },
              }
            : t
        )
      );
    }

    setIsProcessing(false);
    setCurrentTask(null);
  }, [tasks]);

  // 暂停处理
  const handlePauseProcessing = useCallback(() => {
    setIsProcessing(false);
    setTasks(prev => prev.map(t => (t.status === 'processing' ? { ...t, status: 'paused' } : t)));
  }, []);

  // 继续处理
  const handleResumeProcessing = useCallback(() => {
    setIsProcessing(true);
    setTasks(prev => prev.map(t => (t.status === 'paused' ? { ...t, status: 'processing' } : t)));
  }, []);

  // 取消处理
  const handleCancelProcessing = useCallback(() => {
    setIsProcessing(false);
    setTasks(prev =>
      prev.map(t =>
        t.status === 'processing' || t.status === 'paused'
          ? {
              ...t,
              status: 'canceled',
              progress: { ...t.progress, currentPhase: '已取消' },
            }
          : t
      )
    );
    setCurrentTask(null);
  }, []);

  // 清除已完成的任务
  const handleClearCompleted = useCallback(() => {
    setTasks(prev => prev.filter(t => t.status !== 'completed'));
  }, []);

  // 重新处理失败的任务
  const handleRetryFailed = useCallback(() => {
    setTasks(prev =>
      prev.map(t =>
        t.status === 'failed'
          ? {
              ...t,
              status: 'pending',
              progress: { ...t.progress, percentage: 0, currentPhase: '等待开始' },
            }
          : t
      )
    );
  }, []);

  const completedTasks = tasks.filter(t => t.status === 'completed').length;
  const failedTasks = tasks.filter(t => t.status === 'failed').length;
  const activeTasks = tasks.filter(t => t.status === 'processing' || t.status === 'paused').length;

  return (
    <div className={`batch-processor ${className}`}>
      {/* 标题和操作按钮 */}
      <div className='batch-processor__header'>
        <div>
          <h1 className='batch-processor__title'>批量处理</h1>
          <p className='batch-processor__subtitle'>
            批量处理 {tasks.length} 个文件 • 已完成 {completedTasks} • 失败 {failedTasks}
          </p>
        </div>

        <div className='batch-processor__controls'>
          {!isProcessing ? (
            <button
              onClick={handleStartProcessing}
              disabled={tasks.length === 0 || tasks.every(t => t.status === 'completed')}
              className='btn btn-primary flex items-center space-x-2'
            >
              <Play className='w-4 h-4' />
              <span>开始处理</span>
            </button>
          ) : (
            <>
              <button
                onClick={handlePauseProcessing}
                className='btn btn-secondary flex items-center space-x-2'
              >
                <Pause className='w-4 h-4' />
                <span>暂停</span>
              </button>
              <button
                onClick={handleCancelProcessing}
                className='btn btn-danger flex items-center space-x-2'
              >
                <Square className='w-4 h-4' />
                <span>取消</span>
              </button>
            </>
          )}

          {tasks.some(t => t.status === 'paused') && (
            <button
              onClick={handleResumeProcessing}
              className='btn btn-primary flex items-center space-x-2'
            >
              <Play className='w-4 h-4' />
              <span>继续</span>
            </button>
          )}
        </div>
      </div>

      {/* 内容区域 */}
      <div className='batch-processor__content'>
        {/* 文件选择区域 */}
        <div className='batch-processor__grid'>
          {/* 文件列表 */}
          <div className='batch-processor__file-section'>
            <FileList files={selectedFiles} onFilesSelected={handleFilesSelected} className='h-96' />
          </div>

          {/* 处理设置 */}
          <div className='batch-processor__settings-section'>
            <ProcessSettings
              tasks={tasks}
              onSettingsChange={settings => {
                // 更新所有任务的处理设置
                setTasks(prev =>
                  prev.map(task => ({
                    ...task,
                    options: settings,
                  }))
                );
              }}
              className='h-96'
            />
          </div>
        </div>

        {/* 进度监控 */}
        {tasks.length > 0 && (
          <div className='batch-processor__progress-section'>
            <div className='batch-processor__progress-header'>
              <h3 className='batch-processor__progress-title'>
                处理进度 {currentTask && `- ${currentTask.inputFiles[0].name}`}
              </h3>

              <div className='batch-processor__progress-actions'>
                {completedTasks > 0 && (
                  <button onClick={handleClearCompleted} className='btn btn-outline btn-sm'>
                    清除已完成
                  </button>
                )}

                {failedTasks > 0 && (
                  <button onClick={handleRetryFailed} className='btn btn-outline btn-sm'>
                    重试失败
                  </button>
                )}
              </div>
            </div>

            <BatchProgress
              tasks={tasks}
              currentTask={currentTask}
              isProcessing={isProcessing}
              className='min-h-[200px]'
            />
          </div>
        )}

        {/* 状态统计 */}
        {tasks.length > 0 && (
          <div className='batch-processor__stats-section'>
            <div className='batch-stats__card batch-stats__card--total'>
              <div className='batch-stats__value'>{tasks.length}</div>
              <div className='batch-stats__label'>总任务</div>
            </div>

            <div className='batch-stats__card batch-stats__card--completed'>
              <div className='batch-stats__value'>{completedTasks}</div>
              <div className='batch-stats__label'>已完成</div>
            </div>

            <div className='batch-stats__card batch-stats__card--active'>
              <div className='batch-stats__value'>{activeTasks}</div>
              <div className='batch-stats__label'>进行中</div>
            </div>

            <div className='batch-stats__card batch-stats__card--failed'>
              <div className='batch-stats__value'>{failedTasks}</div>
              <div className='batch-stats__label'>失败</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default BatchProcessor;
